package com.design.pattern.observe;

import java.util.ArrayList;
import java.util.List;

public class RealSubject implements Subject {
    private List<Observer> observers;
    private String state;

    public RealSubject() {
        observers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        int i = observers.indexOf(o);
        if (i >= 0) {
            observers.remove(i);
        }
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(this);
        }
    }

    @Override
    public void setState(String state) {
        this.state = state;
        notifyObservers(); // 当状态改变时，通知所有观察者
    }

    @Override
    public String getState() {
        return state;
    }
}